import socket
import re
import multiprocessing
import threading
import gevent
from gevent import monkey
monkey.patch_all()
def service_client(client_socket):
    
    #recv/send接受发送数据额
    recv_data = client_socket.recv(1024)  #  因为前面已经知道IP和端口了
    recv_list =recv_data.decode('utf-8').splitlines()
    req = re.search(r"/[^ ]*",recv_list[0]).group()
    if req == '/':
        req = '/index.html'
    try:
        with open('D:\python\jichuu\Web服务器\moban897'+req,'rb') as f:
            content = f.read()
    except :
        h1 ="HTTP/1.1 404 NOT FOUND\n\r\n"
        content = '<h1>nonono</h1>'
        content = content.encode('utf-8')
    else:
        h1 ="HTTP/1.1 200 OK\n\r\n"
    client_socket.send(h1.encode('utf-8'))
    client_socket.send(content)
    client_socket.close()
    
def main():
    #  socket创建一个套接字
    tcp_server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    tcp_server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)  
    #一定要绑定IP和端口，就跟110一样，是固定的让人随时能知道
    tcp_server.bind(('192.168.124.32',7788))

    #listen使套接字变成可以被动链接
    tcp_server.listen(128)

    #  循环为多个客户端服务
    while True:
        
        #accept等待客户端的链接
        print('等待一个新的客户端的到来~~~~~')
        client_socket,client_add = tcp_server.accept()
        print('一个新的客户端来了~~~~~')
        """#  循环为一个客户服务
        p = multiprocessing.Process(target = service_client,args = (client_socket,))
        p.start()
        client_socket.close()"""
        """#线程用这个,不用再调用一次close
        p = threading.Thread(target = service_client,args = (client_socket,))
        p.start()"""
        # 但最好还是用协程
        gevent.spawn(service_client,client_socket)

        

    #  如果关闭这个客户端相当于银行关了
    tcp_server.close()
    
if __name__ == '__main__':
    main()
